package com.xky.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xky.mapper.BorrowerMapper;
import com.xky.pojo.Book;
import com.xky.pojo.Borrower;
import com.xky.service.BorrowerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Autowired
    private BorrowerMapper borrowerMapper;

    /**
     * 借书人员登记
     *
     * @param borrower 借阅信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBorrower(Borrower borrower) {
        try {
            // 验证必要字段
            if (borrower.getBookCode() == null) {
                throw new IllegalArgumentException("图书编号不能为空");
            }
            if (borrower.getBorrowerName() == null || borrower.getBorrowerName().trim().isEmpty()) {
                throw new IllegalArgumentException("借阅人姓名不能为空");
            }
            if (borrower.getBookName() == null || borrower.getBookName().trim().isEmpty()) {
                throw new IllegalArgumentException("图书名称不能为空");
            }

            // 设置借阅时间
            if (borrower.getBorrowTime() == null) {
                borrower.setBorrowTime(java.time.LocalDateTime.now());
            }

            // 设置借阅状态·
            borrower.setStatus("未归还");

            // 保存借阅记录
            int rows = borrowerMapper.insert(borrower);
            if (rows <= 0) {
                throw new RuntimeException("保存借阅记录失败");
            }
            
            log.info("借阅记录保存成功，借阅编号: {}", borrower.getBorrowerNo());
        } catch (Exception e) {
            log.error("添加借阅记录失败: {}", e.getMessage());
            throw new RuntimeException("添加借阅记录失败: " + e.getMessage());
        }
    }

    /**
     * 归还图书
     */
    @Override
    public void returnBook(Borrower borrower) {
        borrower.setStatus("已归还");
        borrowerMapper.update(borrower,Wrappers.emptyWrapper());
    }

    @Override
    public Borrower getBorrowerByNo(Integer borrowerNo) {
        return borrowerMapper.getBorrowerByNo(borrowerNo);
    }
}
